package com.itboye.mengwu.app.login.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.MainApplication;
import com.itboye.mengwu.app.logincontroller.LoginController;
import com.itboye.mengwu.app.logincontroller.LoginedState;
import com.itboye.mengwu.app.ui.main.MainPresenter;
import com.itboye.mengwu.data.model.PersonDataBean;
import com.itboye.mengwu.main.MainActivity;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Observable;
import java.util.Observer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 2016.5.13
 * 
 * @author liu
 * 
 */
public class LoginActivity extends BaseActivity implements OnClickListener,
		Observer {

	ImageView bindmobil_logo, wixin_login_bt;
	TextView login_text, forget_pass_bt;
	EditText login_input_phonenum, login_input_password;
	Button login_now;
	private String phone;
	private String password;
	MainPresenter mainPresenter;
	TextView loginByMessage;
	TextView new_login_resgister;// 原appSecret:252d40ea15fa4266e1e6854723a1df63-----现在d7fead25487e15bbbd906659bac5a689
	private static final String APP_ID = "wxae95316b3a4998a6";// wxae95316b3a4998a6//wxae95316b3a4998a6
	private IWXAPI api;
	public static String LOGINEXIT = "com.itboye.sunsun.exit";
	MainApplication mainApplication;
	private IntentFilter filter1;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_login;
	}

	@Override
	public void onMyCreate() {
		api = WXAPIFactory.createWXAPI(this, APP_ID);
		mainPresenter = new MainPresenter(this);
		mainApplication= (MainApplication) getApplication();
		// this.login_input_phonenum.setText("18885640674");
		// this.login_input_password.setText("123456");
		filter1 = new IntentFilter(LOGINEXIT);
		registerReceiver(emailBroadcastReceiver, filter1);
	}

	BroadcastReceiver emailBroadcastReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			LoginActivity.this.finish();

		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		registerReceiver(emailBroadcastReceiver,filter1);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_now:

			onLogin();
			break;
		case R.id.forget_pass_bt:
			Intent intent1 = new Intent(this, FindBackPasswordActivity.class);
			startActivity(intent1);
			break;
		case R.id.new_login_resgister:
			Intent intent = new Intent(this, RegiterActivity.class);
			startActivity(intent);
			break;
		case R.id.wixin_login_bt:
			final SendAuth.Req req = new SendAuth.Req();
			req.scope = "snsapi_userinfo";
			req.state = "none";
			req.transaction = "login";
			api.sendReq(req);
			break;
		case R.id.loginByMessage:
			Intent intent2 = new Intent(this, SmsLoginActivity.class);
			startActivity(intent2);
			break;
		default:
			break;
		}
	}

	public void onLogin() {

		phone = login_input_phonenum.getText().toString();
		password = login_input_password.getText().toString();

		// 检查是否是手机号号
		Pattern p = Pattern
				.compile("^((13[0-9])|(17\\d)|(14\\d)|(15[^4,\\D])|(18[0-9]))\\d{8}$");
		Matcher m = p.matcher(phone);
		if (TextUtils.isEmpty(phone)) {
			Toast.makeText(this, "请输入手机号", Toast.LENGTH_SHORT).show();
			return;

		} else if (TextUtils.isEmpty(password)) {
			Toast.makeText(this, "请输入密码", Toast.LENGTH_SHORT).show();
			return;
			//
		} else {
			login_now.setEnabled(false);
			// login_now.setText("登录中...");
			// SharedPreferenceCache.set(SPContants.USERNAME, phone, 1);
			// SharedPreferenceCache.set(SPContants.PASSWORD, password, 1);
			mainPresenter.login(phone, password, 0);

		}
	}

	@Override
	public void update(Observable arg0, Object arg1) {
		showProgressDialog("正在登录中，请稍后", true);
		// TODO Auto-generated method stub
		Log.d("MainActivity", "update 开始");
		ResultEntity entity = super.handlerError(arg1);
		if (entity != null) {
			// Log.d("MainActivity", entity.getEventType());
			// Log.d("MainActivity", entity.getMsg());
			// Log.d("MainActivity", entity.getCode());
			// Log.d("MainActivity", entity.getData().getClass().getName());

			if (entity.getEventType().equals(MainPresenter.LoginSuccessEvent)) {
				whenLoginSuccess(entity);
			} else if (entity.getEventType().equals(
					MainPresenter.RegisterSuccessEvent)) {
				whenRegisterSuccess(entity);
			} else {
				// ByAlert.alert("无法处理的事件!");
				// Log.d("MainActivity" , "无法处理的事件!");
				try {
					closeProgressDialog();
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		login_now.setEnabled(true);
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public void whenRegisterSuccess(ResultEntity result) {
		System.out.print("result.getData" + result.getData());
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public void whenLoginSuccess(ResultEntity result) {
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
		PersonDataBean model = (PersonDataBean) result.getData();
		SPUtils.put(this, null, SpPublicParams.IS_LOGINED, true);
		SPUtils.put(this, null, SpPublicParams.SESSION_CODE, model.getLogin_session_code());
		SPUtils.put(this, null, SpPublicParams.UID, model.getUid());
		SPUtils.put(this, null, SpPublicParams.USER_NAME, model.getUsername());
		SPUtils.put(this, null, SpPublicParams.NICK_NAME, model.getNickname());
		SPUtils.put(this, null, SpPublicParams.SEX, model.getSex());
		SPUtils.put(this, null, SpPublicParams.PHONE_MODEL, model.getMobile());
		SPUtils.put(this, null, SpPublicParams.USERHEAD, model.getHead());
		SPUtils.put(this, null, SpPublicParams.realname, model.getRealname());
		SPUtils.put(this, null, SpPublicParams.COIN, model.getCoin());
		SPUtils.put(this, null, SpPublicParams.FROZINCOIN,
				model.getFronzencoin() == null ? 0 : model.getFronzencoin());
		SPUtils.put(this, null, SpPublicParams.PASSWORD, model.getPassword());
		LoginController.setLoginState(new LoginedState());
		ByAlert.alert("登录成功");
		setResult(102);
		// 发送广播通知更改头像
		Intent intent2 = new Intent("changeavart");
		sendBroadcast(intent2);

		Intent intent = new Intent("changeshopcart");// 更新购物车界面
		sendBroadcast(intent);

		Intent intelogin = new Intent("loginmymengwu");// 我萌登陆刷新
		sendBroadcast(intelogin);

		Intent intentregister = new Intent("finishregister");// 我萌登陆刷新
		sendBroadcast(intentregister);
		if (mainApplication.mainUI!=null) {
			mainApplication.mainUI.setCurrentUI(true);
		}else{
			Intent intent1=new Intent(this, MainActivity.class);
			startActivity(intent1);
		}
		finish();
	}
}
